# capital-minmax.R

# source('capital-minmax.R')
# source('dados.R')
# PlotSimulacaoDispersaoRuina(Danos(5), 100, 8)

## Measure of data dispersion

source('capital.R')

MoreThan <- function(a,b) a > b
LessThan <- function(a,b) a < b

AddIfCmp <- function(T, X, t, x, cmp)
{
	# definir intervalo antes e dps .. [1,t0] e [t2,len]

	t0 <- which(T > t)[1] - 1
	if(cmp(x, X[t0])) {
		t2 <- which(cmp(X, x))[1]

		return(data.frame(
			T=c(T[1:t0], t, T[t2:length(T)]),
			X=c(X[1:t0], x, X[t2:length(T)])))
	}
	data.frame(T=T, X=X)
}

source('progresso.R')

PlotMinMax <- function(Xmin, Ymin, Xmax, Ymax)
{
	X <- sort(c(Xmin, Xmax))
	
}

PlotSimulacaoDispersaoRuina <- function(Danos, u., c.)
{
	nanos <- 100
	c. <- Ccoef(Anos(5), Danos, c.)
	MaxTU <- data.frame(T=c(0,nanos), X=c(u., 99999))
	MinTU <- data.frame(T=c(0,nanos), X=c(u., -99999))
	N <- 1000
	iniciaProgresso(N/20)
	sumU <- 0
	for(n in 1:N) {
		TX <- SimulaGamma(nanos, Danos)
		TU <- TestaRuina_PremioFixo(TX$T, TX$X, u., c., TRUE)
		sumU <- sumU + TU$U[length(TU$U)]
		for(i in 1:length(TU$T)) {
			MaxTU <- AddIfCmp(MaxTU$T, MaxTU$X, TU$T[i], TU$U[i], MoreThan)
			MinTU <- AddIfCmp(MinTU$T, MinTU$X, TU$T[i], TU$U[i], LessThan)
		}
		if(n%%50 == 0)
			progresso()
	}

	MaxTU$X[length(MaxTU$X)] <- MaxTU$X[length(MaxTU$X)-1]
	MinTU$X[length(MinTU$X)] <- MinTU$X[length(MinTU$X)-1]

	plot(MaxTU$T, MaxTU$X, type='l',
		main='Maxima and minima from the simulations (dispersion)',
		cex.main = .9, cex.lab = .8,
		col='blue', lwd=2,
		ylim=c(MinTU$X[length(MinTU$X)],MaxTU$X[length(MaxTU$X)]),
		xlab='Time (in years)',
		ylab='Capital (in billions of dollars)')
	polygon(c(MinTU$T, rev(MaxTU$T)), c(MinTU$X, rev(MaxTU$X)), col=rgb(.98,.98,.98), border=NA)
	lines(MaxTU$T, MaxTU$X, col='blue', lwd=2)
	lines(MinTU$T, MinTU$X, col='red', lwd=2)
	c(MinTU$X[length(MinTU$X)], MaxTU$X[length(MaxTU$X)], sumU/N)
}

